const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const { User } = require("../models");
const { decryptWXData } = require("../utils/wx-decrypt");

const JWT_SECRET = process.env.JWT_SECRET || "secret";
const { success, fail } = require("../utils/response");
const axios = require("axios");

// 微信小程序登录
router.post("/wx-login", async (req, res) => {
    const { code, encryptedData, iv } = req.body;
    console.log("[auth] 微信小程序登录请求:", code);
    console.log(process.env.WX_APPID, process.env.WX_SECRET);
    if (!code) return fail(res, "缺少 code");

    try {
        // 调用微信 jscode2session
        const result = await axios.get("https://api.weixin.qq.com/sns/jscode2session", {
            params: {
                appid: process.env.WX_APPID,
                secret: process.env.WX_SECRET,
                js_code: code,
                grant_type: "authorization_code"
            }
        });
        console.log(result.data)
        const { openid, session_key, errcode, errmsg } = result.data;

        if (!session_key || !openid) {
            console.error("[auth] 微信登录失败:获取session_key和openid失败", result.data);
            return fail(res, errmsg || "微信登录失败:获取session_key和openid失败", 500);
        }
        const userInfo = decryptWXData(session_key, encryptedData, iv);
        console.log("🚀 ~ userInfo:", userInfo)


        if (!userInfo) {
            return fail(res, "解密失败", 500);
        }
        console.log("[auth] 解密成功:", userInfo);

        let user = await User.findOne({ where: { openid } });

        // 如果用户不存在，则创建新用户        
        if (!user) {
            user = await User.create({
                openid,
                nickname: userInfo.nickName,
                avatar: userInfo.avatarUrl,
            });
            console.log("[auth] 新建微信用户:", user.toJSON());
        } else {
            await user.update({
                nickname: userInfo.nickName,
                avatar: userInfo.avatarUrl,
            })
            console.log("[auth] 已存在用户:", user.id);
        }

        // 签发 token
        const token = jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: "7d" });

        return success(res, "登录成功", { token });

    } catch (error) {
        console.error("[auth] 微信登录异常:", error);
        return fail(res, "微信登录失败", 500);
    }
});

// 注册
router.post("/register", async (req, res) => {
    const { phone, password, nickname } = req.body;
    console.log('[auth] 接收到注册请求:', { phone, nickname });

    try {
        const existingUser = await User.findOne({ where: { phone } });
        if (existingUser) {
            console.warn('[auth] 该手机号已注册:', phone);
            return fail(res, "手机号已注册");
        }

        const hashed = await bcrypt.hash(password, 10);
        const user = await User.create({ phone, password: hashed, nickname });
        console.log('[auth] 注册成功:', user.toJSON());

        success(res, "注册成功,为您转跳到登录页！", { userId: user.id });
    } catch (error) {
        console.error('[auth] 注册失败:', error);
        fail(res, "服务器错误，请稍后再试", 500);
    }
});

// 登录
router.post("/login", async (req, res) => {
    const { phone, password } = req.body;
    console.log('[auth] 接收到登录请求:', { phone });

    try {
        const user = await User.findOne({ where: { phone } });
        if (!user) {
            console.warn('[auth] 用户不存在:', phone);
            return fail(res, "用户不存在");
        }

        if (user.status === 0) {
            console.warn('[auth] 用户已被禁用:', phone);
            return fail(res, "用户已被禁用");
        }

        const valid = await bcrypt.compare(password, user.password);
        if (!valid) {
            console.warn('[auth] 密码错误:', phone);
            return fail(res, "密码错误");
        }

        const token = jwt.sign({ userId: user.id }, JWT_SECRET);
        console.log('[auth] 登录成功:', { userId: user.id });

        return success(res, "登录成功", { token });
    } catch (error) {
        console.error('[auth] 登录异常:', error);
        fail(res, "服务器错误，请稍后再试", 500);
    }
});

// 获取用户信息
router.get('/info', async (req, res) => {
    console.log('info接口--[auth] 获取用户信息');

    try {
        // 从请求头中获取 token
        const authHeader = req.headers.authorization || req.headers.token ;
        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            console.warn('[auth] 缺少 token');
            return fail(res, '未提供 token', 401);
        }
        const token = authHeader.split(' ')[1];
        let payload;

        try {
            payload = jwt.verify(token, JWT_SECRET);
            console.log('[auth] token 验证通过:', payload);
        } catch (err) {
            console.warn('[auth] 无效的 token:', token);
            return fail(res, '无效的 token', 401);
        }

        const user = await User.findByPk(payload.userId);
        if (!user) {
            console.warn('[auth] 用户不存在:', payload.userId);
            return fail(res, '用户不存在', 404);
        }

        const userInfo = {
            userId: user.id,
            username: user.nickname || user.phone,
            avatar: user.avatar || 'https://i.pravatar.cc/150?img=3',
            roles: ['Admin'],
            permissions: ['read:system', 'write:system', 'delete:system']
        };

        console.log('[auth] 返回用户信息:', userInfo);
        return success(res, '', userInfo);
    } catch (error) {
        console.error('[auth] 获取用户信息失败:', error);
        return fail(res, '服务器异常，请稍后再试', 500);
    }
});

// 更新资料（示例用途）
router.post("/update", async (req, res) => {
    const { nickname, avatar, region } = req.body;
    console.log('[auth] 更新资料请求:', { nickname, avatar, region });

    try {
        const [affectedRows] = await User.update({ nickname, avatar, region }, { where: { id: 1 } });
        console.log(`[auth] 资料更新完成，影响记录数: ${affectedRows}`);
        res.json({ message: "更新成功" });
    } catch (error) {
        console.error('[auth] 更新资料失败:', error);
        res.status(500).json({ message: "更新失败" });
    }
});

module.exports = router;
